import gtk
import pygtk
def search(self):
#	self.searchterm="regime a"
	self.index_list=[]
	self.search_i=0
	current_tab=self.notebook.get_current_page()
	search_all=True
	found_at_all=False
	if current_tab is -1:
		return
#	self.notebook.set_current_page(0)
	scrolly=self.notebook.get_focus_child()
	view=scrolly.get_child()
	texty=view.get_child()
	buffy=texty.get_buffer()
	start_iter =  buffy.get_start_iter()
	end_iter =  buffy.get_end_iter()
	found = start_iter.forward_search(self.searchterm,0, end_iter)
	if found:
		self.search_success=True
		found_at_all=True
		match_start,match_end = found #add this line to get match_start and match_end
		buffy.select_range(match_start,match_end)
		self.index_list.append(found)
		#self.search_i=
		start_iter=match_end
		search_more(start_iter,end_iter,self.index_list,buffy,self.searchterm)
	if found_at_all is False:
		warning = gtk.MessageDialog(parent=self.excavare, flags=0, type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_OK, message_format="The search term could not be found.")
		warning.set_title("Search")
		warn = warning.run()
		if warn ==gtk.RESPONSE_OK:
			warning.destroy()

def search_more(start_iter,end_iter,index_list,buffy,searchterm):
	found = start_iter.forward_search(searchterm,0, end_iter)
	if found:
		match_start,match_end = found #add this line to get match_start and match_end
		index_list.append(found)
		start_iter=match_end
		search_more(start_iter,end_iter,index_list,buffy,searchterm)

def next_word(self):
	if self.search_success is True:
		term=self.search_entry.get_text()
		if term is not self.searchterm:
			self.search_term=term
			self.search_success = False
			if self.searchterm is not "":
				next_word(self)
		if self.search_i>len(self.index_list):
			return
		self.search_i+=1			
		match_start,match_end=self.index_list[self.search_i]
		scrolly=self.notebook.get_focus_child()
		view=scrolly.get_child()
		texty=view.get_child()
		buffy=texty.get_buffer()
		buffy.select_range(match_start,match_end)
	else:
		self.searchterm=self.search_entry.get_text()
		if self.searchterm is not "":
			search(self)

def prev_word(self):
	if self.search_success is True:
		print self.search_i
		if self.search_i<0:
			return
		self.search_i-=1	
		match_start,match_end=self.index_list[self.search_i]
		scrolly=self.notebook.get_focus_child()
		view=scrolly.get_child()
		texty=view.get_child()
		buffy=texty.get_buffer()
		buffy.select_range(match_start,match_end)
